//
//  WNNetWorkingTools.swift
//  XLWeibo
//
//  Created by 风不会停息 on 2017/7/25.
//  Copyright © 2017年 风不会停息. All rights reserved.
//

import UIKit
import AFNetworking


//  网络请求类型
enum RequestType {
    //  get请求
    case get
    //  post请求
    case post
}

//  网络请求工具类
class HMNetworkTools: AFHTTPSessionManager {
    
    //  单例的全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        //  添加可接收的服务端数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
    }()
    
    //  封装GET和POST请求
    fileprivate func request(type: RequestType, urlStr: String, params: Any?,  finishCallBack: @escaping (Any?, Error?)->()) {
        if type == .get {
            self.get(urlStr, parameters: params, progress: nil, success:
                { (_, response: Any?) in
                    finishCallBack(response, nil)
            }, failure: { (_, error: Error) in
                finishCallBack(nil, error)
            })
        } else {
            self.post(urlStr, parameters: params, progress: nil, success: { (_, response) in
                finishCallBack(response, nil)
            }, failure: { (_, error) in
                finishCallBack(nil, error)
            })
        }
    }
}

// MARK:----OAuth 相关接口整理

extension HMNetworkTools{
    
    /// 获取登录及其所关注的微博用户数据
    ///
    /// - Parameters:
    ///   - access_token: 令牌
    ///   - callBack: 闭包回调
    func requestStatuses(access_token: String, maxId: Int64 = 0, sinceId : Int64 = 0 , callBack: @escaping (Any?, Error?) -> ()) {
        //  接口地址
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        //  接口参数
        let params : [String : Any] = [
            "access_token": access_token,
            "max_id": maxId,
            "since_id": sinceId
        ]
        print(urlStr + "?access_token=\(access_token)")
        //  加载网络数据
        request(type: .get, urlStr: urlStr, params: params, finishCallBack: callBack)
    }
    
    //读取用户数据
    func requestUserinfo(access_token : String , uid : Int64 , callBack : @escaping (Any?,Error?) -> ()) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let params : [String : Any] = [
            
            "access_token" : access_token,
            
            "uid" : uid
        ]
        request(type: .get, urlStr: urlStr, params: params, finishCallBack: callBack)
    }
    
    
    //获取令牌
    func requestAccessToken(code : String , callBack : @escaping (Any?,Error?)->()){
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Redirect_uri
        ]
        
        request(type: .post, urlStr: urlStr, params: params, finishCallBack: callBack)
    }
}














